package com.bxw.forum.controller;


import com.bxw.forum.common.AppResult;
import com.bxw.forum.common.ResultCode;
import com.bxw.forum.config.AppConfig;
import com.bxw.forum.exception.ApplicationException;
import com.bxw.forum.model.Article;
import com.bxw.forum.model.Board;
import com.bxw.forum.model.User;
import com.bxw.forum.service.IArticleService;
import com.bxw.forum.service.IBoardService;
import com.sun.org.apache.regexp.internal.RE;
import com.sun.xml.internal.bind.v2.runtime.SwaRefAdapter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    IArticleService articleService;

    @Resource
    IBoardService boardService;

    /**
     * 新建文章
     * @param boardId 版块id
     * @param title 帖子标题
     * @param content 帖子内容
     * @param request 客户端请求
     * @return
     */
    @RequestMapping("/create")
    public AppResult create(@RequestParam("boardId") @NonNull Long boardId,
                           @RequestParam("title") @NonNull String title,
                           @RequestParam("content") @NonNull String content, HttpServletRequest request) {


        //校验是否被禁言
        //校验版块是否正常
        //插入新建的帖子
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            return AppResult.fail(ResultCode.FAILED_USER_EXISTS);
        }

        Board board = boardService.selectById(boardId);
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());

            return AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS);
        }

        Article article = new Article();
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        article.setTitle(title);
        article.setContent(content);

        articleService.create(article);

        return AppResult.success();

    }

    /**
     * 根据不同版块查询
     * @param boardId 版块ID
     * @return List<Article>
     */
    @RequestMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@RequestParam(value = "boardId",required = false)Long boardId) {


        List<Article> articles;
        if(boardId == null) {

            articles = articleService.selectAll();

        }else {
            articles = articleService.selectAllByBoardId(boardId);
        }

        if(articles == null) {
            articles = new ArrayList<>();
        }

        return AppResult.success(articles);
    }


    /**
     * 根据文章ID关联查询文章详情
     * @param id 文章ID
     * @return Article
     */
    @RequestMapping("/details")
    public AppResult<Article> getDetails(@RequestParam(value = "id") @NonNull Long id,HttpServletRequest request) {

        HttpSession session = request.getSession(false);
        //不用非空判断(做了同一的拦截处理)
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        Article article = articleService.selectDetailById(id);

        if(article == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if(article.getUserId() == user.getId()) {
            article.setOwn(true);
        }else {
            article.setOwn(false);
        }

        return AppResult.success(article);
    }

    /**
     * 更新帖子
     * @param id 帖子ID
     * @param title 帖子标题
     * @param content 帖子内容
     * @param request 客户端请求
     */
    @RequestMapping("/modify")
    public AppResult modify(@RequestParam(value = "id") @NonNull Long id,
                       @RequestParam(value = "title") @NonNull String title,
                       @RequestParam(value = "content") @NonNull String content,
                       HttpServletRequest request) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户状态是否有可以更新
        if(user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        Article article = articleService.selectById(id);

        //判断要更的帖子是否存在
        if(article == null || article.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());

            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断是否是本人的帖子,是否有修改的权限
        if(article.getUserId() != user.getId()) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());

            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }

        //判断帖子状态是否正常
        if(article.getState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());

            return AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED);
        }

        //调用DAO
        articleService.modify(id,title,content);

        log.info("帖子更新成功. Article id = " + id + "User id = " + user.getId() + ".");

        return AppResult.success();
    }

    /**
     * 根据帖子ID修改点赞数
     * @param id 帖子ID
     */
    @RequestMapping("/thumbsUp")
    public AppResult thumbsUp(@RequestParam(value = "id") @NonNull Long id,HttpServletRequest request) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if(user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        articleService.thumbsUpById(id, user.getId());

        return AppResult.success();
    }

    @RequestMapping("/delete")
    public AppResult deleteById(@RequestParam(value = "id") @NonNull Long id,HttpServletRequest request) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if(user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }

        Article article = articleService.selectById(id);

        if(article == null || article.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());

            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        if(article.getState() != 0) {
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());

            return AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED);
        }

        if(user.getId() != article.getUserId()) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());

            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }

        articleService.deleteById(id);

        return AppResult.success();
    }

    @RequestMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request ,
                                                    @RequestParam(value = "userId", required = false) Long userId) {
        // 如果UserId为空，那么从session中获取当前登录的用户Id
        if (userId == null) {
            // 获取Session
            HttpSession session = request.getSession(false);
            // 获取User对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用Service
        List<Article> articles = articleService.selectByUserId(userId);
        // 返回结果
        return AppResult.success(articles);
    }
}
